package com.aurora.source.util.netutil;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.widget.Toast;

import com.aurora.source.util.NetworkUtils;
import com.aurora.source.util.ToastUtils;
import com.aurora.source.util.netutil.listener.ProgressCancelListener;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;
import retrofit2.HttpException;

/**
 * @author: Lance
 * @description: 订阅者 Observer
 * @date: 2018/7/9 10:37
 */
public abstract class SubscriberObserver<T> implements Observer<T>, ProgressCancelListener {

    private ProgressDialogHandler mProgressDialogHandler;
    private Context mContext;
    private boolean isShowDialog;// 是否显示弹窗
    private Disposable mDisposable;

    public SubscriberObserver(Context mContext) {
        this.mContext = mContext;
        mProgressDialogHandler = new ProgressDialogHandler(mContext, this);
    }

    public SubscriberObserver(Context mContext, boolean isShowDialog) {
        this.mContext = mContext;
        this.isShowDialog = isShowDialog;
        mProgressDialogHandler = new ProgressDialogHandler(mContext, this, isShowDialog);
    }

    public SubscriberObserver(Context mContext, String message) {
        this.mContext = mContext;
        this.isShowDialog = true;
        mProgressDialogHandler = new ProgressDialogHandler(mContext, this, message, isShowDialog);
    }

    @Override
    public void onSubscribe(Disposable d) {
        this.mDisposable = d;
        if (!isNetWorking(mContext)) {
            onError("网络不可用");
            onFinish();
        } else {
            showProgressDialog();
        }
    }

    @Override
    public void onNext(T t) {
        onSuccess(t);
    }

    @Override
    public void onError(Throwable e) {
        dismissProgressDialog();
        onFinish();
        if (!isNetWorking(mContext)) {
            onError("网络不可用");
        } else if (e instanceof SocketTimeoutException) {
            onError("服务器响应超时");
        } else if (e instanceof ConnectException) {
            onError("服务器请求超时");
        } else if (e instanceof HttpException) {
            onError("服务器异常");
        } else {
            onError("未知异常：" + e.getMessage());
        }
    }

    @Override
    public void onComplete() {
        dismissProgressDialog();
        onFinish();
    }

    @Override
    public void onCancelProgress() {
        //如果处于订阅状态，则取消订阅
        if (!mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
    }

    //下载成功的回调
    public abstract void onSuccess(T t);

    //下载失败回调
    public abstract void onError(String msg);

    public abstract void onFinish();

    // 显示弹窗
    private void showProgressDialog() {
        if (mProgressDialogHandler != null && isShowDialog) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.SHOW_PROGRESS_DIALOG).sendToTarget();
        }
    }

    // 关闭弹窗
    private void dismissProgressDialog() {
        if (mProgressDialogHandler != null) {
            mProgressDialogHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG)
                    .sendToTarget();
            mProgressDialogHandler = null;
        }
    }

    /**
     * 网络监测
     *
     * @param context
     * @return
     */
    public static boolean isNetWorking(Context context) {
        boolean flag = NetworkUtils.isAvailable(context);
        try {
            if (!flag) {
                ToastUtils.showSingletonShort(context, "当前设备网络异常，请检查后再重试！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }
}
